<template>
    <div>
        <n-tag v-for="tab in tabsStore.tabs" ref="tabRefs" :key="tab.path"
            class="px-15 mx-5 cursor-pointer hover:color-success"
            :type="tabsStore.activeTab === tab.path ? 'primary' : 'default'" :closable="tabsStore.tabs.length > 1"
            @click="handleTabClick(tab.path)" @close.stop="tabsStore.removeTab(tab.path)"
            @contextmenu.prevent="handleContextMenu($event, tab)">
            {{ tab.title }}
        </n-tag>

        <ContextMenu v-if="contextMenuOption.show" v-model:show="contextMenuOption.show"
            :current-path="contextMenuOption.currentPath" :x="contextMenuOption.x" :y="contextMenuOption.y" />
    </div>
</template>
  
<script setup>
import ContextMenu from "./ContextMenu.vue";
import { useTabsStore } from "@/stores/tabs";

const route = useRoute();
const router = useRouter();
const tabsStore = useTabsStore();
const tabRefs = ref([]);

const contextMenuOption = reactive({
    show: false,
    x: 0,
    y: 0,
    currentPath: "",
});

watch(
    () => route.path,
    () => {
        const { name, fullPath: path } = route;
        const title = route.meta?.title;
        tabsStore.addTab({ name, path, title });
    },
    { immediate: true }
);

watch(
    () => tabsStore.activeIndex,
    async (activeIndex) => {
        await nextTick();
        const activeTabElement = tabRefs.value[activeIndex]?.$el;
        if (!activeTabElement) return;
    },
    { immediate: true }
);

const handleTabClick = (path) => {
    tabsStore.setActiveTab(path);
    router.push(path);
};

function showContextMenu() {
    contextMenuOption.show = true;
}
function hideContextMenu() {
    contextMenuOption.show = false;
}
function setContextMenu(x, y, currentPath) {
    Object.assign(contextMenuOption, { x, y, currentPath });
}

// 右击菜单
async function handleContextMenu(e, tabItem) {
    const { clientX, clientY } = e;
    hideContextMenu();
    setContextMenu(clientX, clientY, tabItem.path);
    await nextTick();
    showContextMenu();
}
</script>
  
<style>
.n-tag__close {
    box-sizing: content-box;
    border-radius: 50%;
    font-size: 12px;
    padding: 2px;
    transform: scale(0.9);
    transform: translateX(5px);
    transition: all 0.3s;
}
</style>